package com.swak.frame.extension.adapter;

import java.util.Objects;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;

import com.swak.frame.dto.base.BizScenario;
import com.swak.frame.extension.executor.ExtensionExecutor;
import com.swak.frame.extension.provider.RiskWhiteListExtPtProvider;

public class RiskWhiteListAdapter implements SmartInitializingSingleton {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private ExtensionExecutor extensionExecutor;

	private RiskWhiteListExtPtProvider riskWhiteListExtPtProvider;

	public RiskWhiteListAdapter(ExtensionExecutor extensionExecutor) {
		this.extensionExecutor = extensionExecutor;
	}

	public boolean isWhiteList(String pin) {
		Set<String> whiteList = riskWhiteListExtPtProvider.whiteListConfig();
		// 白名单属性是否配置,未配置放行
		if (CollectionUtils.isEmpty(whiteList)) {
			return false;
		}
		boolean isMatch = whiteList.stream().anyMatch(wpin -> Objects.equals(wpin, pin));
		// 不匹配，说明该pin不在白名单中，不放行
		if (isMatch) {
			logger.warn("风控白名单过滤通过! PIN：{},whiteList:{}", new Object[] { pin, whiteList });
			return true;
		}
		return false;
	}

	@Override
	public void afterSingletonsInstantiated() {
		if (riskWhiteListExtPtProvider == null) {
			this.riskWhiteListExtPtProvider = extensionExecutor.locateComponent(RiskWhiteListExtPtProvider.class,
					BizScenario.valueOf(RiskWhiteListExtPtProvider.WRISK_BIZ_ID));
		}
	}
}
